package com.hb.guli.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.guli.common.base.result.R;
import com.hb.guli.service.edu.entity.*;
import com.hb.guli.service.edu.entity.form.CourseInfoForm;
import com.hb.guli.service.edu.entity.vo.CoursePublishVo;
import com.hb.guli.service.edu.entity.vo.CourseQueryVo;
import com.hb.guli.service.edu.entity.vo.CourseVo;
import com.hb.guli.service.edu.entity.vo.WebCourseQueryVo;
import com.hb.guli.service.edu.feign.OssFileService;
import com.hb.guli.service.edu.feign.VodMediaService;
import com.hb.guli.service.edu.mapper.*;
import com.hb.guli.service.edu.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author jack
 * @since 2023-06-30
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionMapper courseDescriptionMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private ChapterMapper chapterMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CourseCollectMapper courseCollectMapper;
    @Autowired
    private OssFileService ossFileService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveCourseInfoForm(CourseInfoForm courseInfoForm) {
        // 保存 Course
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        course.setStatus(Course.COURSE_DRAFT);
        baseMapper.insert(course);

        // 保存 CourseDescription
        final CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.insert(courseDescription);

        return course.getId();
    }

    @Override
    public CourseInfoForm getCourseInfoById(String id) {
        final CourseInfoForm courseInfoForm = new CourseInfoForm();
        final Course course = baseMapper.selectById(id);
        BeanUtils.copyProperties(course, courseInfoForm);
        final CourseDescription courseDescription = courseDescriptionMapper.selectById(id);
        courseInfoForm.setDescription(courseDescription.getDescription());
        return courseInfoForm;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCourseInfoForm(CourseInfoForm courseInfoForm) {
        // 更新 Course
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        course.setStatus(Course.COURSE_DRAFT);
        baseMapper.updateById(course);

        // 更新 CourseDescription
        final CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.updateById(courseDescription);

    }

    @Override
    public Page<CourseVo> selectPage(Long page, Long limit, CourseQueryVo courseQueryVo) {
        Page<CourseVo> pageParam = new Page<>(page, limit);

        final QueryWrapper<CourseVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("edu_course.gmt_create");
        final String title = courseQueryVo.getTitle();
        final String teacherId = courseQueryVo.getTeacherId();
        final String subjectId = courseQueryVo.getSubjectId();
        final String subjectParentId = courseQueryVo.getSubjectParentId();
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(teacherId)) {
            queryWrapper.eq("teacher_id", teacherId);
        }
        if (!StringUtils.isEmpty(subjectId)) {
            queryWrapper.eq("subject_id", subjectId);
        }
        if (!StringUtils.isEmpty(subjectParentId)) {
            queryWrapper.eq("subject_parent_id", subjectParentId);
        }

        List<CourseVo> records = baseMapper.selectPageByQueryVo(pageParam, queryWrapper);

        return pageParam.setRecords(records);
    }

    // 删除视频封面
    @Override
    public boolean deleteCoverById(String id) {
        final Course course = baseMapper.selectById(id);
        if (course != null) {
            final String cover = course.getCover();
            if (!StringUtils.isEmpty(cover)) {
                final R r = ossFileService.deleteFile(cover);
                return r.getSuccess();
            }
        }
        return false;
    }

    @Autowired
    private VodMediaService vodMediaService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeCourseById(String id) {

        // 跟据 courseId 删除 Video
        final QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", id);
        final List<Video> videos = videoMapper.selectList(videoQueryWrapper);
        final List<String> collect = videos.stream().map(Video::getVideoSourceId)
                .filter(Objects::nonNull).collect(Collectors.toList());
        vodMediaService.removeVideoByIdList(collect);
        final List<String> ids = videos.stream().map(Video::getId).collect(Collectors.toList());
        videoMapper.deleteBatchIds(ids);

        // 跟据 courseId 删除 Chapter
        final QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", id);
        chapterMapper.delete(chapterQueryWrapper);

        // 跟据 courseId 删除 CourseDescription
        final QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("course_id", id);
        commentMapper.delete(commentQueryWrapper);

        // 跟据 courseId 删除 CourseCollect
        final QueryWrapper<CourseCollect> courseCollectQueryWrapper = new QueryWrapper<>();
        courseCollectQueryWrapper.eq("course_id", id);
        courseCollectMapper.delete(courseCollectQueryWrapper);


        // 跟据 courseId 删除 CourseDescription
        courseDescriptionMapper.deleteById(id);


        this.deleteCoverById(id);
        return this.removeById(id);
    }

    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {

        return baseMapper.selectCoursePublishById(id);
    }

    @Override
    public boolean publishCourseById(String id) {
        final Course course = new Course();
        course.setId(id);
        course.setStatus(Course.COURSE_NORMAL);
        return this.updateById(course);
    }

    @Override
    public List<Course> webSelectList(WebCourseQueryVo webCourseQueryVo) {
        final QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        // 查询已发布的课程
        courseQueryWrapper.eq("status",Course.COURSE_NORMAL);

        if(StringUtils.isNotEmpty(webCourseQueryVo.getSubjectParentId())){
            courseQueryWrapper.eq("subject_parent_id", webCourseQueryVo.getSubjectParentId());
        }

        if (StringUtils.isNotEmpty(webCourseQueryVo.getSubjectId())) {
            courseQueryWrapper.eq("subject_id", webCourseQueryVo.getSubjectId());
        }

        if (StringUtils.isNotEmpty(webCourseQueryVo.getBuyCountSort())) {
            courseQueryWrapper.orderByDesc("buy_count");
        }
        if (StringUtils.isNotEmpty(webCourseQueryVo.getGmtCreateSort())) {
            courseQueryWrapper.orderByDesc("gmt_create");
        }
        if (StringUtils.isNotEmpty(webCourseQueryVo.getPriceSort())) {
            courseQueryWrapper.orderByDesc("price");
        }

        return baseMapper.selectList(courseQueryWrapper);
    }

}
